<template>
  <a-skeleton :loading="loading" active>
    <div class="leaderboard">
      <div class="leaderboard__top flex justify-between mb-5">
        <div class="leaderboard__title text-3xl font-bold text-gray-800">
          {{ boardTitle }}
        </div>
        <div class="leaderboard__controls flex items-center">
          <a-select
            class="w-48"
            placeholder="选择排序方式"
            v-model:value="selectedSort"
            @change="handleChange"
          >
            <a-select-option value="1">按答题次数排序</a-select-option>
            <a-select-option value="2">按正确率排序</a-select-option>
            <a-select-option value="3">按获得积分排序</a-select-option>
          </a-select>
          <a-button class="ml-4 flex" @click="refreshData" type="primary">
            <reload-outlined class="mt-1"/>
            <span>刷新</span>
          </a-button>
        </div>
      </div>
      <div class="leaderboard__table overflow-auto">
        <a-table
          :columns="columns"
          :dataSource="finalData"
          :pagination="pagination"
          :rowClassName="rowClassName"
        />
      </div>
    </div>
  </a-skeleton>
</template>

<script setup>
import { ref, onMounted, watch, computed, h } from "vue";
import { ReloadOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { useClassStore } from "@/stores/class";
import { usePointStore } from "@/stores/point";

const loading = ref(true);
const boardTitle = ref("排行榜");
const columns = [
  {
    title: "排名",
    dataIndex: "rank",
    key: "rank",
    customRender: ({ text }) => {
      if (text === 1) {
        return h("span", { class: "rank first-rank" }, "🥇");
      } else if (text === 2) {
        return h("span", { class: "rank second-rank" }, "🥈");
      } else if (text === 3) {
        return h("span", { class: "rank third-rank" }, "🥉");
      } else {
        return h("span", { class: "rank" }, text);
      }
    },
  },
  {
    title: "姓名",
    dataIndex: "stu_name",
    key: "stu_name",
  },
  {
    title: "答题次数",
    dataIndex: "attempts",
    key: "attempts",
  },
  {
    title: "正确率",
    dataIndex: "correctnessRate",
    key: "correctnessRate",
    customRender: ({ text }) => `${text}%`,
  },
  {
    title: "获得积分",
    dataIndex: "points",
    key: "points",
  },
];

const data = ref([]);
const finalData = ref([]);
const selectedSort = ref("1");
const classStore = useClassStore();
const pointStore = usePointStore();

const pageSize = ref(8);
const currentPage = ref(1);
const pagination = computed(() => ({
  current: currentPage.value,
  total: data.value.length,
  pageSize: pageSize.value,
  pageSizeOptions: [],
  showSizeChanger: true,
  showQuickJumper: true,
  onChange: (page, size) => {
    currentPage.value = page;
    pageSize.value = size;
  },
}));
const fetchStudents = async (currentClassNo) => {
  try {
    const response = await window.electronAPI.getStuDataByClassNo(
      currentClassNo
    );
    if (response.success) {
      data.value = response.students.map((student) => {
        let correctnessRate = 0;
        if (student.attempts > 0) {
          correctnessRate = Math.round(
            (student.corrects / student.attempts) * 100
          );
        } else {
          correctnessRate = 0;
        }
        return {
          ...student,
          attempts: student.attempts || 0,
          correctnessRate,
          points: student.points || 0,
        };
      });
      handleChange(selectedSort.value);
    } else {
      data.value = [];
      message.error("获取学生数据失败：" + response.error);
    }
  } catch (error) {
    console.error("Error fetching student data:", error);
    message.error("获取学生数据失败：" + error.message);
  } finally {
    loading.value = false;
  }
};

const handleChange = (value) => {
  selectedSort.value = value;
  switch (value) {
    case "1":
      finalData.value = [...data.value].sort((a, b) => b.attempts - a.attempts);
      break;
    case "2":
      finalData.value = [...data.value].sort(
        (a, b) => b.correctnessRate - a.correctnessRate
      );
      break;
    case "3":
      finalData.value = [...data.value].sort((a, b) => b.points - a.points);
      break;
    default:
      finalData.value = data.value;
  }
  assignRanks();
};

const assignRanks = () => {
  finalData.value = finalData.value.map((item, index) => ({
    ...item,
    rank: index + 1,
  }));
};

const refreshData = () => {
  const currentClassNo = classStore?.selectedClass?.class_no;
  if (!currentClassNo) {
    return;
  }
  loading.value = true;
  fetchStudents(currentClassNo);
};

onMounted(async () => {
  await classStore.initializeClass();
  const initializeClassNo = classStore?.selectedClass?.class_no;
  if (initializeClassNo) {
    await fetchStudents(initializeClassNo);
  }
  pointStore.$subscribe((mutation, state) => {
    if (mutation.storeId === "point") {
      refreshData();
    }
  });
  classStore.$subscribe((mutation, state) => {
    if (mutation.storeId === "class") {
      refreshData();
    }
  });
  loading.value = false;
});
</script>

<style scoped lang="less">
.leaderboard {
  width: 100%;
  padding: 40px 40px 20px 40px;
  border-radius: 10px;
  background: linear-gradient(
    180deg,
    rgba(253, 226, 151, 1) 0%,
    rgba(254, 246, 224, 1) 16.33%,
    rgba(255, 255, 255, 1) 23.41%,
    rgba(255, 255, 255, 1) 100%
  );
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: auto;

  .leaderboard__top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.4rem;

    .leaderboard__title {
      font-size: 24px;
      font-weight: 600;
      color: rgba(51, 51, 51, 0.9);
      text-align: left;
      position: relative;
    }

    .leaderboard__controls {
      display: flex;
      align-items: center;
    }
  }

  .leaderboard__table {
    .ant-table {
      .ant-table-thead > tr > th {
        background-color: transparent !important;
        @apply py-3 px-4 border-b text-left text-lg font-medium;
      }

      .ant-table-tbody > tr > td {
        @apply py-3 px-4 border-b text-gray-700;
      }

      .ant-table-tbody > tr:hover > td {
        @apply bg-transparent;
      }
    }
  }

  .rank {
    display: flex;
    align-items: center;
  }

  .first-rank {
    color: gold;
    font-weight: bold;
  }

  .second-rank {
    color: silver;
    font-weight: bold;
  }

  .third-rank {
    color: #cd7f32; 
    font-weight: bold;
  }
}
</style>
